﻿using MQTTnet;
using MQTTnet.Server;
using System.Net;
using System.Text;

namespace MqttServer1
{
    class Program
    {
        static async Task Main(string[] args)
        {
            // 配置MQTT服务端选项
            var options = new MqttServerOptionsBuilder()
            .WithDefaultEndpointBoundIPAddress(IPAddress.Parse("127.0.0.1")) // 设置服务器地址  
            .WithDefaultEndpointPort(1883) // 默认端口  
            //.WithDefaultEndpoint()
            .Build();
            options.DefaultEndpointOptions.IsEnabled = true;

            // 创建MQTT服务端
            var mqttServer = new MqttFactory().CreateMqttServer(options);

            mqttServer.ClientConnectedAsync += MqttServer_ClientConnectedAsync;
            mqttServer.ClientDisconnectedAsync += MqttServer_ClientDisconnectedAsync;

            //处理接收到的消息
            mqttServer.ApplicationMessageEnqueuedOrDroppedAsync += MqttServer_ApplicationMessageEnqueuedOrDroppedAsync;

            // 启动MQTT服务端
            await mqttServer.StartAsync();
            Console.WriteLine("MQTT Server started and listening on port 1883");

            // 保持程序运行
            Console.WriteLine("Press Enter to exit.");
            Console.ReadLine();

            // 停止MQTT服务端
            await mqttServer.StopAsync();
            Console.WriteLine("MQTT Server stopped.");

            Console.WriteLine("按任意键退出......");
            Console.ReadKey();
        }

        private static Task MqttServer_ApplicationMessageEnqueuedOrDroppedAsync(ApplicationMessageEnqueuedEventArgs e)
        {
            Console.WriteLine("MQTT Server Received message:");
            Console.WriteLine($"ClientId: {e.SenderClientId}");
            Console.WriteLine($"ReceiverClientId: {e.ReceiverClientId}");
            Console.WriteLine($"Topic: {e.ApplicationMessage.Topic}");
            Console.WriteLine($"Payload: {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
            return Task.CompletedTask;
        }

        private static Task MqttServer_ClientDisconnectedAsync(ClientDisconnectedEventArgs e)
        {
            Console.WriteLine($"Client disconnected: {e.ClientId}");
            return Task.CompletedTask;
        }

        private static Task MqttServer_ClientConnectedAsync(ClientConnectedEventArgs e)
        {
            Console.WriteLine($"Client connected: {e.ClientId}");
            return Task.CompletedTask;
        }
    }
}
